<script setup lang="ts">
import {
    createEnterpriseAPI,
    getIndustryListAPI,
    uploadAPI,
} from "@/apis/enterprise";
import type { Industry } from "@/types/enterprise";
import {
    ElMessage,
    type FormInstance,
    type FormRules,
    type UploadInstance,
    type UploadRawFile,
    type UploadRequestOptions,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";

const addForm = reactive({
    name: "", // 企业名称
    legalPerson: "", // 法人
    registeredAddress: "", // 注册地址
    industryCode: "", // 所在行业
    contact: "", // 企业联系人
    contactNumber: "", // 联系人电话
    businessLicenseUrl: "", // 营业执照url
    businessLicenseId: "", // 营业执照id
});

// 行业列表
const industryList = ref<Industry[]>([]);
// 获取行业列表
const getIndustryList = async () => {
    const res = await getIndustryListAPI();
    console.log(res);
    // 保存行业列表
    industryList.value = res.data;
};

onMounted(() => {
    getIndustryList();
});

// 上传文件
const uploadFile = async (options: UploadRequestOptions) => {
    console.log(options);
    // 准备 fromData 对象
    const fromData = new FormData();
    // 文件
    fromData.append("file", options.file);
    // 上传类型
    fromData.append("type", "businessLicense");
    const res = await uploadAPI(fromData);
    // 保存营业执照 id 和 url
    addForm.businessLicenseId = res.data.id;
    addForm.businessLicenseUrl = res.data.url;
    // 主动触发校验(校验通过，错误提示就会消失)
    addFormRef.value?.validateField("businessLicenseId");
};

// 上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传。
const beforeUpload = (rawFile: UploadRawFile) => {
    // 大小限制：5M
    const size5M = 5 * 1024 * 1024;
    // 格式限制：.png .jpg .jpeg
    const AcceptType = ["image/png", "image/jpeg", "image/jpg"];
    if (rawFile.size > size5M) {
        ElMessage.error("文件大小不能超过5M");
        return false;
    } else if (AcceptType.includes(rawFile.type) === false) {
        ElMessage.error("仅支持扩展名：.png .jpg .jpeg");
        return false;
    }
};

// 删除了文件
const onFileRemove = () => {
    // 清空营业执照信息
    addForm.businessLicenseId = "";
    addForm.businessLicenseUrl = "";
};

// 用于统一表单校验
const addFormRef = ref<FormInstance>();
// 表单校验
const addFormRules = reactive<FormRules<typeof addForm>>({
    name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
    legalPerson: [{ required: true, message: "请输入法人", trigger: "blur" }],
    registeredAddress: [
        { required: true, message: "请输入注册地址", trigger: "blur" },
    ],
    industryCode: [
        { required: true, message: "请选择所属行业", trigger: "change" },
    ],
    contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
    contactNumber: [
        { required: true, message: "请输入联系电话", trigger: "blur" },
        { pattern: /^1\d{10}$/, message: "请输入正确的手机号" },
    ],
    businessLicenseId: [
        { required: true, message: "请上传营业执照", trigger: "change" },
    ],
    businessLicenseUrl: [
        { required: true, message: "请上传营业执照", trigger: "change" },
    ],
});

// 路由器，用于跳转页面
const router = useRouter();
// 提交时按钮 loading 状态
const submitLoading = ref(false);
const onSubmit = async () => {
    try {
        // 统一表单校验
        await addFormRef.value?.validate();
        // 按钮变成 loading 状态，避免多次点击提交
        submitLoading.value = true;
        // 提交表单
        await createEnterpriseAPI(addForm);
        // 轻提示
        ElMessage.success("添加成功");
        // 返回上一页
        router.back();
    } catch (error) {
        ElMessage.error("请按要求完善企业信息");
    } finally {
        // 不管成功失败，关闭按钮 loading
        submitLoading.value = false;
    }
};

const uploadRef = ref<UploadInstance>();
// 重置表单
const onReset = () => {
    // 清空 url
    addForm.businessLicenseUrl = "";
    // 重置常规表单
    addFormRef.value?.resetFields();
    // 重置清空已上传的文件列表
    uploadRef.value?.clearFiles();
};
</script>

<template>
    <div class="add-enterprise">
        <header class="add-header">
            <el-page-header content="添加企业" @back="$router.back()" />
        </header>
        <main class="add-main">
            <div class="form-container">
                <div class="title">企业信息</div>
                <div class="form">
                    <el-form ref="addFormRef" label-width="100px" :model="addForm" :rules="addFormRules">
                        <el-form-item label="企业名称" prop="name">
                            <el-input v-model="addForm.name" clearable />
                        </el-form-item>
                        <el-form-item label="法人" prop="legalPerson">
                            <el-input v-model="addForm.legalPerson" clearable />
                        </el-form-item>
                        <el-form-item label="注册地址" prop="registeredAddress">
                            <el-input v-model="addForm.registeredAddress" clearable />
                        </el-form-item>
                        <el-form-item label="所在行业" prop="industryCode">
                            <!-- 下拉菜单 -->
                            <el-select v-model="addForm.industryCode" clearable>
                                <el-option v-for="item in industryList" :key="item.industryCode"
                                    :value="item.industryCode" :label="item.industryName" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="企业联系人" prop="contact">
                            <el-input v-model="addForm.contact" clearable />
                        </el-form-item>
                        <el-form-item label="联系电话" prop="contactNumber">
                            <el-input v-model="addForm.contactNumber" :maxlength="11" clearable />
                        </el-form-item>
                        <el-form-item label="营业执照" prop="businessLicenseId">
                            <el-upload ref="uploadRef" name="file" drag :limit="1" :http-request="uploadFile"
                                accept=".png,.jpg,.jpeg" :before-upload="beforeUpload" :on-remove="onFileRemove">
                                <el-button size="small" type="primary">点击上传</el-button>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M
                                    </div>
                                </template>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    {{ addForm }}
                </div>
            </div>
        </main>
        <footer class="add-footer">
            <div class="btn-container">
                <el-button @click="onReset">重置</el-button>
                <el-button :loading="submitLoading" type="primary" @click="onSubmit">
                    确定
                </el-button>
            </div>
        </footer>
    </div>
</template>

<style scoped lang="scss">
.add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        background: #f4f6f8;
        padding: 20px 130px;

        .form-container {
            background-color: #fff;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;

                    .el-form-item {
                        width: 50%;
                    }
                }
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
    }
}
</style>
